package com.itheima.gateway.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description: 登录拦截的全局过滤器
 * @Version: V1.0
 */
//@Order(1)  //如果有多个过滤器， Order的值越小越优先执行
//@Component   // 扫描
public class LoginFilter implements GlobalFilter { //, Ordered


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1 获取当前request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2 获取token参数
        String token = request.getQueryParams().getFirst("token");

        //2.1 获取不到token 拦截
        if (StringUtils.isBlank(token)) {
            // 设置状态码  401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 拦截请求
            return response.setComplete();
        }

        //2.2  获取token，判断 token是否为admin
        // 3 不是拦截
        if (!"admin".equals(token)) {
            // 设置状态码  401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 拦截请求
            return response.setComplete();
        }


        // 放行
        return chain.filter(exchange);
    }

    /**
     * 如果有多个过滤器， Order的值越小越优先执行
     * @return
     */
//    @Override
//    public int getOrder() {
//        return 1;
//    }
}
